package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    //  获取容器中IPermissionService的实现类对象，并注入Bean
    @Autowired
    private IPermissionService permissionService;

    //  查询方法
    @RequestMapping("/list")
    @RequiredPermission(name = "权限列表", expression = "permission:list")
    public String list(Model model, QueryObject qo){
        //  调用Service层的query方法
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        //  将获取到的数据设置到模型中
        model.addAttribute("pageResult", pageInfo);
        //  找视图/WEB-INF/views/permission/list.ftl
        return "permission/list";
    }

    //  加载方法
    @RequestMapping("/reload")
    @ResponseBody
    @RequiredPermission(name = "权限加载", expression = "permission:reload")
    public JsonResult reload(){
        try {
            permissionService.reload();
            return new JsonResult(true, "加载成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new JsonResult(false, "加载失败");
        }
    }

    //  删除方法
    @RequiredPermission(name = "权限删除", expression = "permission:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            //  判断id是否存在
            if (id != null) {
                //  调用Service层的deleteById方法
                permissionService.deleteById(id);
            }
            return new JsonResult(true, "删除成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new JsonResult(false, "删除失败");
        }
    }
    
}
